﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Microsoft.Office.Interop.Word;
using System.Text;

public partial class forms_Custom_ExcelTest_WordToHtml : System.Web.UI.Page
{
    public string strHtml;
    protected void Page_Load(object sender, EventArgs e)
    {
        GetPathByDocToHTML();
    }
    private void GetPathByDocToHTML()
    {
        try
        {
            strHtml = string.Empty;
            //if (!Directory.Exists("./ExcelTest/wordTemp"))
            //{
            //    Directory.CreateDirectory("./ExcelTest/wordTemp");
            //}
            //string newname = DateTime.Now.ToString("yyyyMMddHHmmss") + ".doc";
            //wordFile.PostedFile.SaveAs("./ExcelTest/wordTemp/" + newname);
            //string path = Request.Url.AbsoluteUri.ToString().Substring(0, Request.Url.AbsoluteUri.IndexOf("Default.aspx")) + "/wordTemp/测试.docx";
            ChangeWordToHtml(Server.MapPath("/InSiteWebApplication/forms/Custom/ExcelTest/wordTemp/测试1.docx"), Server.MapPath("/InSiteWebApplication/forms/Custom/ExcelTest/wordTemp/"), "测试");
            string content = File.ReadAllText(Server.MapPath("/InSiteWebApplication/forms/Custom/ExcelTest/wordTemp/测试.html"), Encoding.Default);
            strHtml = content;
        }
        catch
        {

        }
    }

    private void ChangeWordToHtml(string path, string savePath, string wordFileName)
    {
        ApplicationClass word = new ApplicationClass();
        Type wordType = word.GetType();
        Documents docs = word.Documents;
        Type docsType = docs.GetType();
        Document doc = (Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { (object)path, true, true });
        Type docType = doc.GetType();
        string strSaveFileName = savePath + wordFileName + ".html";
        if (File.Exists(strSaveFileName))
        {
            new FileInfo(strSaveFileName).Attributes = FileAttributes.Normal;
            File.Delete(strSaveFileName);
        }
        object saveFileName = (object)strSaveFileName;
        docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, WdSaveFormat.wdFormatFilteredHTML });
        docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
        wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
    }
}